from flask import Flask,send_file,render_template
import os

app = Flask(__name__)

def sysip():
    sys_cmd = "sudo ifconfig wlan0 | grep inet | head -n 1 | awk '{print $2}'"
    sysip = os.popen(sys_cmd).read()        
    return sysip

@app.route('/<dir>/<filename>')
def download(dir,filename):
    response = send_file("/data/data/com.termux/files/home/"+dir+"/"+filename, as_attachment=True, attachment_filename=filename)
    return response

@app.route('/<dir>')
def index(dir):
    fs = []
    ip  = sysip()
    for root, dirs, files in os.walk("/data/data/com.termux/files/home/"+dir, topdown=False):
        for name in files:
            if len(name.split('.'))>1 and os.path.exists(r'/data/data/com.termux/files/home/'+dir+"/"+name):
                file_info = {}
                file_info['file_name'] = name
                file_info['file_url'] = 'http://'+ip+':2209/'+dir+"/"+name
                fs.append(file_info)
    return render_template('index.html',fs = fs)

@app.route('/')
def index_home():
    fs = []
    ip  = sysip()
    for file in os.listdir('/data/data/com.termux/files/home'):
        if os.path.isdir('/data/data/com.termux/files/home/'+file):
            file_info = {}
            file_info['file_name'] = file
            file_info['file_url'] = 'http://'+ip+':2209/'+file
            fs.append(file_info)
    return render_template('index.html',fs = fs)


if __name__ == '__main__':
    app.run(host='0.0.0.0',port = 2209, debug=False)

